package dev.lpf.springsecurity;

import java.util.Optional;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/admin")
public class AdminTestController {

    @RequestMapping("/home")
    public String productInfo(){
        return " admin home page ";
    }

    @RequestMapping("/user")
    public String userInfo() {
        String userName = "";
        String userPwd = null;
        String userRoles = null;
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if(principal instanceof UserDetails){
            userName = ((UserDetails) principal).getUsername();
            userRoles = ((UserDetails) principal).getAuthorities().toString();
            userPwd = ((UserDetails) principal).getPassword();
        }else {
            userName = principal.toString();
        }
        Object details = SecurityContextHolder.getContext().getAuthentication().getDetails();
        Object authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        Object credentials = SecurityContextHolder.getContext().getAuthentication().getCredentials();
        StringBuilder sb = new StringBuilder();
        sb.append("User:\n")
            .append("userName:").append(Optional.ofNullable(userName).orElse("null").toString()).append("\n")
            .append("userRoles:").append(Optional.ofNullable(userRoles.toString()).orElse("null")).append("\n")
            .append("userPwd:").append(Optional.ofNullable(userPwd).orElse("null").toString()).append("\n")
            .append("details:").append(Optional.ofNullable(details).orElse("null").toString()).append("\n")
            .append("authorities:").append(Optional.ofNullable(authorities).orElse("null").toString()).append("\n")
            .append("credentials:").append(Optional.ofNullable(credentials).orElse("null").toString());
        System.out.println(sb.toString());
        return sb.toString();
    }
}
